function [ ZeroCross ModMaxPos ModMaxVal ac1 ] = CalcACModMaxPos( wtSignal )

cant_modmax = 1;
cant_zc = 1;

[lwtSignal cantSigs] = size(wtSignal);

ModMaxPos = nan(1,cantSigs);
ModMaxVal = nan(1,cantSigs);
ZeroCross = nan(1,cantSigs);
ac1 = nan(1,cantSigs);

if( all( wtSignal == 0 ) )
    return
end

wtSignal = mat2cell(wtSignal, lwtSignal, ones(1, cantSigs));
ac1 = cellfun(@(a)(conv(a, flipud(a)) ), wtSignal, 'UniformOutput', false );
ac1 = cellfun(@(a)(a(lwtSignal:end) ), ac1, 'UniformOutput', false );
ac1 = cellfun(@(a)( normalize(a) ), ac1, 'UniformOutput', false );

interp_idx = (1:0.1:lwtSignal)';

ac1_interp = cellfun(@(a)(spline( 1:lwtSignal, a, interp_idx ) ), ac1, 'UniformOutput', false );

iZeroCrossPos_ac1 = cellfun(@(a)(myzerocros(a) ), ac1, 'UniformOutput', false );

ZeroCross = cellfun(@(a,b)(linear_interp_zc(a, b, lwtSignal, cant_zc) ), iZeroCrossPos_ac1, ac1, 'UniformOutput', false );

ModMaxPos_ac1 = cellfun(@(a)( modmax( a, 2, 0, 0 ) ), ac1_interp, 'UniformOutput', false );

[ModMaxPos ModMaxVal ] = cellfun(@(a,b,c)( modmaxpos_detect(a, b, interp_idx, c, cant_modmax) ), ModMaxPos_ac1, ZeroCross, ac1_interp, 'UniformOutput', false  );

ZeroCross = colvec(cell2mat(ZeroCross));
ModMaxPos = colvec(cell2mat(ModMaxPos));
ModMaxVal = colvec(cell2mat(ModMaxVal));

function ZeroCross = linear_interp_zc(iZeroCrossPos_ac1, ac1, lwtSignal, cant_zc)


ZeroCross = nan(cant_zc,1);

if( isempty(iZeroCrossPos_ac1))
    return
else
    for ii = 1:min(length(iZeroCrossPos_ac1), cant_zc)
        if( iZeroCrossPos_ac1(ii) < lwtSignal )
            if( sign(ac1(iZeroCrossPos_ac1(ii))) ~= sign(ac1(iZeroCrossPos_ac1(ii)+1)) )
                ZeroCross(ii) = iZeroCrossPos_ac1(ii) - ac1(iZeroCrossPos_ac1(ii)) / ( ac1(iZeroCrossPos_ac1(ii)+1) - ac1(iZeroCrossPos_ac1(ii)) );
            else
                ZeroCross(ii) = (iZeroCrossPos_ac1(ii)-1) - ac1(iZeroCrossPos_ac1(ii)-1) / ( ac1(iZeroCrossPos_ac1(ii)) - ac1(iZeroCrossPos_ac1(ii)-1) );
            end
        end   
    end
end

function [ModMaxPos ModMaxVal ] = modmaxpos_detect(ModMaxPos_ac1, ZeroCross, interp_idx, ac1_interp, cant_modmax)


ModMaxPos = nan(cant_modmax,1);
ModMaxVal = nan(cant_modmax,1);

if( ~isempty(ModMaxPos_ac1) && ~isempty(ZeroCross) )
    for ii = 1:min( length(ModMaxPos_ac1), cant_modmax)
        
        if( ii <= length(ZeroCross) )
            valid_ac1_max_idx = find(interp_idx(ModMaxPos_ac1) > ZeroCross(ii));
        else
            valid_ac1_max_idx = find(interp_idx(ModMaxPos_ac1) > ModMaxPos(ii-1) );
        end
        
        if( ~isempty(valid_ac1_max_idx) )
            ModMaxPos(ii) = interp_idx(ModMaxPos_ac1(valid_ac1_max_idx(1)));
            ModMaxVal(ii) = ac1_interp(ModMaxPos_ac1(valid_ac1_max_idx(1)));
        end
    end
else
    return
end


function a = normalize(a)

    if(a(1) ~= 0 )
        a = 1/a(1)*a;
    end
        
